﻿@inject IMaterialService MaterialService

<RadzenCard Variant="Variant.Filled" Style="height : 100%;">
    <RadzenStack>
        <SearchFormPartial Model="_searchRequestDto" QueryHandler="QueryHandler"></SearchFormPartial>
        <SearchTablePartial @ref="_requestTable" T="MaterialInfoResponseDto" ServerData="ServerReload"
                            SearchPartial="_searchPartial"
                            AddHandler="AddHandler"
                            EditHandler="EditHandler">

        </SearchTablePartial>
    </RadzenStack>
</RadzenCard>

@code {
    private MaterialSearchRequestDto _searchRequestDto = new();
    private IEnumerable<MaterialInfoResponseDto> _pagedData = new List<MaterialInfoResponseDto>();
    private SearchPartialInfo _searchPartial = new();
    private SearchTablePartial<MaterialInfoResponseDto> _requestTable = new();
    private int _totalItems;

    [CascadingParameter]
    public MaterialIndex? MaterialIndex { get; set; }

    async Task QueryHandler(MouseEventArgs args)
    {
        await _requestTable.ReloadServerData();
    }

    Task AddHandler(MouseEventArgs args)
    {
        MaterialIndex?.SetDynamicComponentType(typeof(MaterialEdit));

        return Task.CompletedTask;
    }

    Task EditHandler(MouseEventArgs args, MaterialInfoResponseDto model)
    {
        MaterialIndex?.SetKey(model.Id);
        MaterialIndex?.SetDynamicComponentType(typeof(MaterialEdit));
        return Task.CompletedTask;
    }

    /// <summary>
    /// Here we simulate getting the paged, filtered and ordered data from the server
    /// </summary>
    private async Task<ODataServiceResult<MaterialInfoResponseDto>> ServerReload(LoadDataArgs state)
    {
        if (state.Skip != null) _searchRequestDto.Page = (int)(state.Skip + 1);
        if (state.Top != null) _searchRequestDto.Limit = (int)state.Top;
        var result = await MaterialService.QueryMaterialsByPage(_searchRequestDto);

        if (result is { Succeeded: true })
        {
            _pagedData = result.Data;
            _totalItems = result.TotalCount;
        }

        return new ODataServiceResult<MaterialInfoResponseDto>() { Count = _totalItems, Value = _pagedData };
    }

    protected override async Task OnInitializedAsync()
    {
        await base.OnInitializedAsync();

        //var authenticationState = await AuthenticationStateProvider.GetAuthenticationStateAsync();

        _searchPartial.IsAdd = true;
        _searchPartial.IsEdit = true;
        _searchPartial.IsDelete = true;
        //_searchPartial.IsImportExcel = (await AuthorizationService.AuthorizeAsync(authenticationState.User, nameof(ApiRoutes.Database.ImportDatabase))).Succeeded;
        //_searchPartial.IsExportExcel = (await AuthorizationService.AuthorizeAsync(authenticationState.User, nameof(ApiRoutes.Database.ExportDatabase))).Succeeded;
    }


}
